// pages/accounting_voucher/accounting_voucher.js
let listBehavior = require('../../behavior/list')

let assistObj = {},
    optionObj = {}

Page({
  behaviors: [ listBehavior, ],
  /**
   * 页面的初始数据
   */
  data: {
    auth: {},
    // list: [],                 // 凭证列表
    // total: 0,
    // page: 1,
    // limit: 30,
    // scrollReset: false,

    // 筛选条件
    keyList: [ { field_id: 'abstract', field_name: '摘要', }, ],
    searchList: [
      { field_name: '会计期', type: 'reference1', field_id: ['account_period_s', 'account_period_e'], optionList: [], optionId: 'account_period', optionName: 'account_period', },
      { field_name: '会计科目', type: 'reference1', field_id: 'account_id', optionList: [], optionId: 'id', },
      { field_name: '科目级别', type: 'num', field_id: 'account_level', },
      { field_name: '金额', type: 'digit', field_id: ['amount_s', 'amount_e'], },
      { field_name: '凭证号', type: 'num', field_id: ['voucher_no_s', 'voucher_no_e'], },
      { field_name: '录入方式', type: 'reference1', field_id: 'input_type', optionList: [
        { id: 'manual', name: '手动', },
        { id: 'automatic', name: '自动', },
      ], optionId: 'id', optionName: 'name', },
    ],
    quickFlag: false,
    accountVal: '',
  },

  toggleFlag(e) {
    this.setData({
      quickFlag: !this.data.quickFlag,
    })
  },
  // 混合查询
  searchComb(e) {
    let val = e.detail.iptVal
    this.query.abstract = val
    if(!val) delete this.query.abstract
    this.getFirstPage()
  },
  searchQuick(e) {
    let obj = e.detail,
        query = {},
        abstract = this.query.abstract
    Object.values(obj).forEach(item => {
      let { field_id, val, } = item
      if(Array.isArray(field_id)) {
        val.forEach((v, i) => {
          if(![undefined, null, '',].includes(v)) query[field_id[i]] = v
        })
      } else if(![undefined, null, '',].includes(val)) {
        query[field_id] = val
      }
    })
    this.query = query
    if(abstract) this.query.abstract = abstract
    this.setAcctVal()
    this.getFirstPage()
  },
  setAcctVal() {
    let query = this.query,
        arr = []

    if(query.account_period_s || query.account_period_e) {
      if(query.account_period_s) {
        let s = (query.account_period_s + '月').split('')
        s.splice(-3, 0, '年')
        arr.push(s.join(''))
      }
      if(query.account_period_e) {
        let s = (query.account_period_e + '月').split('')
        s.splice(-3, 0, '年')
        arr.push(s.join(''))
      }
    }
    this.setData({
      accountVal: arr.join(' - '),
    })
  },

  navTo(e) {
    let { item, } = e.currentTarget.dataset,
        { voucher_id, input_type, } = item
    // console.log(item.input_type);
    // return
    wx.navigateTo({
      url: `../accounting_voucher_detl/accounting_voucher_detl?voucher_id=${voucher_id}&canedit=${input_type.toLowerCase() === 'manual' ? 1 : 0}`,
    })
  },

  // 接口
  ready() {
    this.query = {}

    // 获取会计期、会计科目 选项列表
    let p0 = this.getOptionList(0, 'account_period_s,account_period_e', 3, 'Account/query_all_account_period', { limit: 0, page: 1, }),
        p1 = this.getOptionList(1, 'account_id', 3, 'Account/select_account')

    Promise.all([p0, p1]).then(res => {
      let searchList = this.data.searchList,
          obj = {}
      res.forEach((item, i) => {
        obj = { ...obj, ...item, }
      })
      searchList.forEach(item => {
        let field_id = item.field_id,
            key = Array.isArray(field_id) ? field_id.join(',') : field_id
        if(obj[key]) item.optionList = obj[key]

        if(key === 'account_period_s,account_period_e' && !item.dfltVal) {
          console.log(obj[key], item.optionId)
          let curr = new Date(),
              year = curr.getFullYear(),
              month = curr.getMonth() + 1,
              filterItems = obj[key].filter(item => item.account_year === year && item.account_month === month)
          if(filterItems.length) {
            // let first = obj[key][0],
            let first = filterItems[0],
                val = first[item.optionId]
            item.dfltVal = [ val, val, ]
            this.query = {
              account_period_e: val,
              account_period_s: val,
            }
          }

          this.setAcctVal()
        }
      })

      this.setData({
        searchList,
      })
    })

    // 获取会计科目、辅助核算项目
    return new Promise((resolve, reject) => {
      Promise.all([this.getSubjectList(), this.getAssistProject()]).then(res => {
        let optionList = res[0].accountId,
            assistList = res[1].assistObj
        optionObj = {}
        assistObj = {}

        optionList.forEach((item, i) => {
          if(item.assist_account_json) {
            optionObj[item.account_id] = item
            item.assist_account_value_arr = item.assist_account_value.split(',')
          }
        })
        assistList.forEach(item => assistObj[item.row_id] = item)

        resolve()
      })
    })
  },
  // 获取会计科目
  getSubjectList() {
    return this.getOptionList(0, 'accountId', 3, 'Account/query_account_last', { page: 1, limit: 0, oby: 'account_id', })
  },
  // 获取辅助核算项目
  getAssistProject() {
    return this.getOptionList(0, 'assistObj', 1, 'AllAssistAccount/select_all_assist_account', {})
  },
  getOptionList() {
    return new Promise((resolve, reject) => {
      let [ method, key, v, url, params, ] = arguments
      let request = method ? wx.$get : wx.$post
      request(v, url, params).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        rows = rows.flat()
        resolve({ [key]: rows, })
      })
    })
  },
  getDataList() {
    if(!this.data.auth.tableSee) {
      let { total, page, limit, } = this.data
      wx.$toast('抱歉，您没有权限查看该模块')
      this.setData({
        total,
        page,
        limit,
      })
      return
    }

    let { page, limit, list, } = this.data,
        post = {
          page,
          limit,
          voucher_word: '记',
          ...this.query,
        }
    wx.$post(3, 'Voucher/query_all_voucher', post).then(res => {
      if(res.errcode !== 0) return
      let rows = res.data.row
      rows.forEach(item => {
        // console.log(item.quantity_account_1_row_id);
        let { account_id, } = item
        if(optionObj[account_id]) {
          let arr = optionObj[account_id].assist_account_value_arr,
              assistArr = []
          arr.forEach((label, l) => {
            assistArr.push({
              label,
              val: item[`quantity_account_${l + 1}_value`] || '',
            })
          })
          item.assistArr = assistArr
        }
      })
      if(page !== 1) rows = [ ...list, ...rows, ]
      this.setData({
        list: rows,
        total: res.data.total,
        // total: 0,
        page,
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.$setBarTitle();
    let { entity, account_period_s, account_period_e, include_id, } = options,
        auth = await wx.$getAuth(entity)
    this.data.auth = auth

    // 科目余额表调过来会传递 起始会计期、科目id(account_id) 作为默认查询参数
    if(account_period_s || account_period_e || include_id) {
      this.query = {
        account_id: include_id || '',
        account_period_e: account_period_e || '',
        account_period_s: account_period_s || '',
      }
      this.setAcctVal()

      let { searchList, } = this.data
      searchList[0].dfltVal = [ account_period_s, account_period_e, ]
      searchList[1].dfltVal = include_id
      this.setData({
        searchList,
      })
    }

    await this.ready()
    this.getDataList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})
